package cn.iocoder.yudao.module.picturebook.service.favorites;

import cn.iocoder.yudao.module.picturebook.dal.dataobject.book.BookDO;
import cn.iocoder.yudao.module.picturebook.service.book.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.*;

import cn.iocoder.yudao.module.picturebook.controller.admin.favorites.vo.*;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.favorites.FavoritesDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.picturebook.dal.mysql.favorites.FavoritesMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.module.picturebook.enums.ErrorCodeConstants.*;

/**
 * 用户收藏 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class FavoritesServiceImpl implements FavoritesService {

    @Resource
    private FavoritesMapper favoritesMapper;
    @Resource
    private BookService bookService;

    // ... existing code ...
    @Override
    public Long createFavorites(FavoritesSaveReqVO createReqVO) {
        // 参数校验
        if (createReqVO == null) {
            return null;
        }

        // 插入
        FavoritesDO favorites = BeanUtils.toBean(createReqVO, FavoritesDO.class);
        favoritesMapper.insert(favorites);

        // 添加空值检查
        if (favorites.getId() == null) {
            return null;
        }

        // 返回
        return favorites.getId();
    }

    @Override
    public void updateFavorites(FavoritesSaveReqVO updateReqVO) {
        // 参数校验
        if (updateReqVO == null) {
            return;
        }
        if (updateReqVO.getId() == null) {
            return;
        }

        // 校验存在
        if (favoritesMapper.selectById(updateReqVO.getId()) == null) {
            return;
        }
        // 更新
        FavoritesDO updateObj = BeanUtils.toBean(updateReqVO, FavoritesDO.class);
        favoritesMapper.updateById(updateObj);
    }

    @Override
    public boolean deleteFavorites(Long bookId, Long userId) {
        // 参数校验
        if (bookId == null || userId == null) {
            return false;
        }

        return favoritesMapper.deleteByBookIdAndUserId(bookId, userId);
    }


    @Override
    public void deleteFavoritesListByIds(List<Long> ids) {
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            return;
        }

        // 删除
        favoritesMapper.deleteByIds(ids);
    }


    private void validateFavoritesExists(Long id) {
        // 参数校验
        if (id == null) {
            return;
        }

        if (favoritesMapper.selectById(id) == null) {
            log.error("[getFavorites][id({}) 不存在]", id);
            // 不抛出异常，仅记录日志
            return;
        }
    }

    @Override
    public FavoritesDO getFavorites(Long id) {
        // 参数校验
        if (id == null) {
            return null;
        }

        return favoritesMapper.selectById(id);
    }

    @Override
    public PageResult<FavoritesRespVO> getFavoritesPage(FavoritesPageReqVO pageReqVO) {
        // 参数校验
        if (pageReqVO == null) {
            return PageResult.empty();
        }

        try {
            PageResult<FavoritesDO> favoritesDOPageResult = favoritesMapper.selectPage(pageReqVO);
            if (favoritesDOPageResult == null || favoritesDOPageResult.getList() == null) {
                return PageResult.empty();
            }

            //获取里面的书籍id去查询书然后存储到FavoritesRespVO用循环
            List<FavoritesDO> favoritesDOList = favoritesDOPageResult.getList();
            List<FavoritesRespVO> respVOList = new ArrayList<>();
            for (FavoritesDO favoritesDO : favoritesDOList) {
                if (favoritesDO != null) {
                    BookDO book = null;
                    try {
                        book = bookService.selectById(favoritesDO.getBookId());
                    } catch (Exception e) {
                        log.error("[getFavorites][id({}) 获取书籍信息失败]", favoritesDO.getBookId(), e);
                        // 获取书籍信息失败，继续处理其他数据
                    }
                    FavoritesRespVO respVO = BeanUtils.toBean(favoritesDO, FavoritesRespVO.class);
                    respVO.setBook(book);
                    respVOList.add(respVO);
                }
            }
            return new PageResult<>(respVOList, favoritesDOPageResult.getTotal());
        } catch (Exception e) {
            // 出现异常时返回空结果
            return PageResult.empty();
        }
    }

    @Override
    public PageResult<FavoritesDO> getFavoritesPageByUserId(FavoritesPageReqVO pageReqVO) {
        // 参数校验
        if (pageReqVO == null) {
            return PageResult.empty();
        }

        return favoritesMapper.selectPageByUserId(pageReqVO);
    }

    @Override
    public Integer getFavoritesByUserIdAndBookId(Long bookId, Long userId) {
        // 参数校验
        if (bookId == null || userId == null) {
            return 0;
        }

        try {
            FavoritesDO favoritesDO = favoritesMapper.selectOne(
                    FavoritesDO::getBookId, bookId,
                    FavoritesDO::getUserId, userId
            );

            if (favoritesDO == null) {
                return 0;
            }

            Integer collectionType = favoritesDO.getCollectionType();
            return collectionType == null ? 0 : collectionType;
        } catch (Exception e) {
            // 出现异常时返回默认值
            return 0;
        }
    }
// ... existing code ...


}